<template>
	<view class="flex jcsb aic __unauth_tips" v-if='showUnauthTips && unAuthItemCount > 0' @tap="open">
		<view class="flex aic">
			<text class="iconfont danger-color mr_8">&#xe66c;</text>
			您有{{ unAuthItemCount}}项基础功能未开启，将影响接单和提现
		</view>
		<view class="flex aic primary-color">
			<text>去开启</text>
		</view>
	</view>
	<pd-popup ref='popup' @change="($event : boolean) => opened = $event">
		<view class="__auth_check">
			<view class="__auth_check_title flex jcsb aic mb_16">
				<text class="_text_size_36 _text_weight_bold ">请开启下列功能</text>
				<!-- <text class="iconfont" @tap="popup?.close()">&#xe6c9;</text> -->
			</view>
			<view class="__auth_check_desc _text_size_28 danger-color">
				未全部开启将影响订单推送、状态通知、接单、车费提现等
			</view>
			<view class="__auth_check_items">
				<view v-for="item in authConfigs" :key='item.type' class="__auth_check_item flex jcsb aic">
					<view>
						<view class="__auth_check_item_title _text_size_32 mb_8 _text_weight_bold">{{item.title}}</view>
						<view class="__auth_check_item_desc _text_size_28">{{item.desc}}</view>
					</view>
					<view class="flex aic primary-color" v-if="!item.status" @click='itemHandler(item)' style="font-size: 28rpx;">
						{{item.btnConfig.text}}
						<text class="iconfont _text_size_28">&#xe66a;</text>
					</view>
					<view v-else class="primary-color" @click='itemHandler(item)'>
						<text class="iconfont">&#xe62c;</text>
					</view>
				</view>
			</view>
		</view>
	</pd-popup>
</template>

<script lang="ts" setup>
import Store from '@/store';
import PD from '../libs';
import PdPopup from './pd-popup.vue';
import type {WxUserPermission} from '@/pd-libs/libs/wx-types';
import { APP_ROUTES } from '../enum/app-routes';
import ApiHelp from '@/api/api-help';
withDefaults(defineProps<{
	showUnauthTips : boolean
}>(), {
	showUnauthTips : false, //是否显示未授权提示
});

const opened = ref(false); //当前授权弹窗是否处于打开状态
const popup = ref<InstanceType<typeof PdPopup>>();
const authConfigs = ref(PD.AppDeclare.getCurrentApp()!.preAuthItems);
const unAuthItemCount = computed(() => {//未完成的授权数量
	return authConfigs.value.filter(item => !item.status).length;
});

// watch(() => opened.value, (n : boolean) => {
// 	n && uni.hideTabBar();
// 	!n && uni.showTabBar();
// });


onShow(() => {
	if (opened.value) {
		check(true);
	};
});
const itemHandler = async (item : typeof authConfigs.value[0]) => {
	//接单宝、拼哒进行埋点
	if(item.point){
		PD.WxHelp.wxReport(item.point);
	};
	if (['scope.userLocationBackground', 'scope.record', 'scope.userLocation'].includes(item.type)) {
		const result = await PD.WxHelp.getPermission(item.type as WxUserPermission);
		//没有授权过，走申请授权，授权过就打开设置
		if (result === undefined && item.type !== 'scope.userLocationBackground') {
			item.status = Boolean(await PD.UniHelp.authorize(item.type as WxUserPermission));
			//只有申请授权的需要主动检测，其他都通过onshow钩子去检测
			check();
		} else {
			await PD.UniHelp.openSetting();
		};
	} else if (item.type === 'isRulesRead') {//学习接单规则，该状态的变更来自于学习规则页面的操作
		PD.UniHelp.navTo(APP_ROUTES.studyPickOrderRules);
	} else {//关注公众号
		PD.UniHelp.navTo(`${APP_ROUTES.webView}?src=${PD.AppDeclare.getCurrentApp()!.attentionArticleSrc}&title=关注公众号`);
	};
};


/**
 * 从login数据中获取初始状态，并同步到配置项中
 * @param {Boolean} forceUpdate 是否强制更新，是则会从服务端拉取最新信息
 */

const check = (forceUpdate = false) : Promise<void> => {
	return new Promise(async (r,j) => {
		for (let i = 0; i < authConfigs.value.length; i++) {//内部使用了await 所以这里不使用map/forEach来循环
			const v = authConfigs.value[i];
			if (['scope.userLocationBackground', 'scope.record', 'scope.userLocation'].includes(v.type)) {
				v.status = Boolean(await PD.WxHelp.getPermission(v.type as WxUserPermission));
			};
			if (v.type === 'isAttention') {
				v.status = forceUpdate ? await ApiHelp.User.isAttention() : Boolean(Store.user().loginResponse.subscribe);
			};
			if (v.type === 'isRulesRead') {
				v.status = Boolean(Store.user().loginResponse.study_rule);
			};
		};
		//检测后如果都设置了，则关闭dialog
		if (authConfigs.value.every(v => v.status === true)) {
			popup.value?.close();
			r();
		} else {
			j();
		};
	});
};

check();

const open = () => {
	!opened.value && popup.value?.open();
	PD.WxHelp.wxReport('home_openfunction_240223');
};

defineExpose({
	open,
	check
});

</script>

<style lang="less" scoped>
.__unauth_tips {
	font-size: 24rpx;
	background: #ffe7ec;
	padding: 16rpx 30rpx;
	.iconfont {
		margin-right: 6rpx;
		font-size: 30rpx;
	}
}
.__auth_check {
	padding: 32rpx 24rpx;
	background: #fff;
	border-radius: 16rpx 16rpx 0 0;
	&_item {
		padding: 15rpx 0;
		&_desc {
			color: #aaa;
		}
		&:not(:last-child) {
			border-bottom: 1px solid #f1f1f1;
		}
		.iconfont {
			margin-left: 10rpx;
		}
	}
}
</style>